import { _decorator, Component, Node, Event, EventTouch, EventMouse, Sprite, Color, Prefab, instantiate, Vec3, tween, sys, Tween, v3, color, Enum, UIOpacity } from 'cc';
const { ccclass, property, menu } = _decorator;

@ccclass('EnhancedDoubleClick')
@menu('UI/EnhancedDoubleClick')
export class EnhancedDoubleClick extends Component {
   // 基础设置
    @property({
        tooltip: "双击识别时间间隔(毫秒)",
        min: 100,
        max: 1000
    })
    public interval: number = 400;

    @property({
        tooltip: "是否阻止双击时的单击事件触发"
    })
    public preventSingleClick: boolean = true;

    // 视觉反馈设置
    @property({
        tooltip: "启用视觉反馈",
        displayName: "Enable Feedback"
    })
    public enableFeedback: boolean = true;

    @property({
        type: Enum({
            NONE: 0,
            SCALE: 1,
            COLOR: 2,
            PARTICLE: 3,
            COMBO: 4,
            RIPPLE: 5
        }),
        tooltip: "反馈类型",
        visible() { return this.enableFeedback; }
    })
    public feedbackType: number = 1;

    @property({
        type: Color,
        tooltip: "高亮颜色",
        visible() { return this.enableFeedback && this.feedbackType === 2; }
    })
    public highlightColor: Color = color(0, 255, 0);

    @property({
        type: Prefab,
        tooltip: "粒子效果预制体",
        visible() { return this.enableFeedback && this.feedbackType === 3; }
    })
    public particlePrefab: Prefab | null = null;

    @property({
        type: Prefab,
        tooltip: "涟漪效果预制体",
        visible() { return this.enableFeedback && this.feedbackType === 5; }
    })
    public ripplePrefab: Prefab | null = null;

    @property({
        tooltip: "启用调试日志",
        displayName: "Enable Debug Log"
    })
    public debugMode: boolean = true;

    @property({
        tooltip: "点击最小间隔时间(毫秒)",
        min: 50,
        max: 500
    })
    minClickInterval: number = 100;

    private _lastEventTime: number = 0;

    // 私有变量
    private _lastClickTime: number = 0;
    private _clickTimer: any = null;
    private _isDoubleClick: boolean = false;
    private _originalScale: Vec3 = v3(1, 1, 1);
    private _waitingForSecondClick: boolean = false;
    private _originalColor: Color = color(255, 255, 255); // 添加缺失的原始颜色属性

    onLoad() {
        // 保存原始状态
        const sprite = this.node.getComponent(Sprite);
        if (sprite) {
            this._originalColor = sprite.color.clone();
            this._logDebug(`原始颜色保存为: ${this._originalColor.toString()}`);
        }
        this._originalScale = this.node.scale.clone();
        this._logDebug(`原始缩放保存为: ${this._originalScale.toString()}`);
        
        this._registerEvent();
    }

    private _registerEvent() {
        this.node.on(Node.EventType.TOUCH_START, this._onTouchStart, this);
        this.node.on(Node.EventType.MOUSE_DOWN, this._onMouseDown, this);
        this._logDebug("事件监听器已注册");
    }

    private _onTouchStart(event: EventTouch) {
        this._logDebug(`触摸开始 @ ${event.getLocation().toString()}`);
        this._handleClick(event);
    }

    private _onMouseDown(event: EventMouse) {
        this._logDebug(`鼠标按下 @ ${event.getLocation().toString()}`);
        this._handleClick(event);
    }

    private _handleClick(event: Event) {
        const now = Date.now();
    
        // 添加最小点击间隔保护
        if (now - this._lastEventTime < this.minClickInterval) {
            this._logDebug("点击过于频繁，忽略");
            return;
        }
        this._lastEventTime = now;
        
        this._logDebug(`处理点击事件，当前状态: 
            lastClickTime: ${this._lastClickTime}
            isDoubleClick: ${this._isDoubleClick}
            waitingForSecondClick: ${this._waitingForSecondClick}
            timer: ${this._clickTimer ? "存在" : "无"}`);

        if (this._waitingForSecondClick && now - this._lastClickTime < this.interval) {
            this._logDebug("检测到第二次点击 - 确认为双击");
            this._clearTimer();
            this._waitingForSecondClick = false;
            this._isDoubleClick = true;
            this._handleDoubleClick(event);
        } else {
            this._logDebug("第一次点击或间隔时间过长");
            this._clearTimer();
            this._lastClickTime = now;
            this._waitingForSecondClick = true;
            this._isDoubleClick = false;
            
            this._clickTimer = setTimeout(() => {
                if (this._waitingForSecondClick && !this._isDoubleClick) {
                    this._logDebug("单击超时确认 - 触发单击事件");
                    this._waitingForSecondClick = false;
                    this._handleSingleClick(event);
                }
            }, this.interval);
            this._logDebug(`设置单击超时定时器: ${this.interval}ms`);
        }
    }

    private _handleSingleClick(event: Event) {
        this._logDebug("处理单击事件开始");
        if (!this.preventSingleClick || !this._isDoubleClick) {
            this._logDebug("触发 single-click 事件");
            this.node.emit('single-click', event);
        } else {
            this._logDebug("单击事件被阻止(因 preventSingleClick 设置)");
        }
        this._resetState();
    }

    private _handleDoubleClick(event: Event) {
        this._logDebug("处理双击事件开始");
        this.node.emit('double-click', event);
        
        if (this.enableFeedback) {
            this._logDebug(`执行视觉反馈，类型: ${this.feedbackType}`);
            this._playFeedbackEffect(event);
        }
        this._resetState();
    }

    private _playFeedbackEffect(event: Event) {
        if (!this._isDoubleClick) {
            this._logDebug("反馈被阻止(非双击状态)");
            return;
        }

        switch (this.feedbackType) {
            case 1: // SCALE动画
                this._logDebug("开始SCALE动画反馈");
                Tween.stopAllByTarget(this.node);
                
                tween(this.node)
                    .call(() => this._logDebug("SCALE动画阶段1: 缩小"))
                    .to(0.1, { scale: v3(0.9, 0.9, 1) })
                    .call(() => this._logDebug("SCALE动画阶段2: 放大"))
                    .to(0.1, { scale: v3(1.1, 1.1, 1) })
                    .call(() => this._logDebug("SCALE动画阶段3: 恢复"))
                    .to(0.1, { scale: this._originalScale })
                    .call(() => {
                        this.node.setScale(this._originalScale);
                        this._logDebug("SCALE动画完成");
                    })
                    .start();
                break;

            case 2: // 颜色变化
                this._logDebug("开始COLOR动画反馈");
                const sprite = this.node.getComponent(Sprite);
                if (sprite) {
                    tween(sprite)
                        .call(() => this._logDebug(`颜色从 ${sprite.color.toString()} 变化到 ${this.highlightColor.toString()}`))
                        .to(0.1, { color: this.highlightColor })
                        .call(() => this._logDebug(`颜色恢复为 ${this._originalColor.toString()}`))
                        .to(0.3, { color: this._originalColor })
                        .start();
                } else {
                    this._logDebug("颜色反馈失败: 节点缺少Sprite组件");
                }
                break;

            // 其他反馈类型...
        }
    }

    private _resetState() {
        this._logDebug("重置组件状态");
        this._isDoubleClick = false;
        this._waitingForSecondClick = false;
        this._lastClickTime = 0;
    }

    private _clearTimer() {
        if (this._clickTimer) {
            this._logDebug("清除现有定时器");
            clearTimeout(this._clickTimer);
            this._clickTimer = null;
        }
    }

    private _logDebug(message: string) {
        if (this.debugMode) {
            L.log(`[DoubleClick][${Date.now()}] ${message}`, {
                lastClickTime: this._lastClickTime,
                isDoubleClick: this._isDoubleClick,
                waiting: this._waitingForSecondClick,
                hasTimer: !!this._clickTimer
            });
        }
    }

    onDestroy() {
        this._logDebug("组件销毁中...");
        this._clearTimer();
        this.node.off(Node.EventType.TOUCH_START, this._onTouchStart, this);
        this.node.off(Node.EventType.MOUSE_DOWN, this._onMouseDown, this);
    }
}